package com.ruoyi.project.channel.businessCapital.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.channel.bankInfo.domain.BankInfo;
import com.ruoyi.project.channel.bankInfo.service.IBankInfoService;
import com.ruoyi.project.channel.businessCaptialSetting.domain.BusinessCaptialSetting;
import com.ruoyi.project.channel.businessCaptialSetting.service.IBusinessCaptialSettingService;
import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.project.channel.businessInfo.service.IBusinessInfoService;
import com.ruoyi.project.channel.businessRate.domain.BusinessRate;
import com.ruoyi.project.channel.businessRate.service.IBusinessRateService;
import com.ruoyi.project.channel.payerBusinessInfo.domain.PayerBusinessInfo;
import com.ruoyi.project.channel.payerBusinessInfo.service.IPayerBusinessInfoService;
import com.ruoyi.project.channel.payerInfo.domain.PayerInfo;
import com.ruoyi.project.channel.payerInfo.service.IPayerInfoService;
import com.ruoyi.project.channel.userGoodsInfo.domain.UserGoodsInfo;
import com.ruoyi.project.channel.userGoodsInfo.service.IUserGoodsInfoService;
import com.ruoyi.project.channel.vwBusinessCashStat.domain.VwBusinessCashStat;
import com.ruoyi.project.channel.vwBusinessCashStat.service.IVwBusinessCashStatService;
import com.ruoyi.project.pay.ThirdPayerServiceImpl;
import com.ruoyi.project.system.user.domain.User;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.channel.businessCapital.domain.BusinessCapital;
import com.ruoyi.project.channel.businessCapital.service.IBusinessCapitalService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.web.client.RestTemplate;

/**
 * 商户提现信息操作处理
 *
 * @author zero
 * @date 2019-05-04
 */
@Controller
@RequestMapping("/channel/businessCapital")
public class BusinessCapitalController extends BaseController {
    private String prefix = "channel/businessCapital";

    @Autowired
    private IBusinessCapitalService businessCapitalService;
    @Autowired
    private IBankInfoService bankInfoService;
    @Autowired
    private IVwBusinessCashStatService vwBusinessCashStatService;
    @Autowired
    private IBusinessInfoService businessInfoService;
    @Autowired
    private IUserGoodsInfoService userGoodsInfoService;
    @Autowired
    private IBusinessCaptialSettingService businessCaptialSettingService;
    @Autowired
    private ThirdPayerServiceImpl thirdPayerService;
    @Autowired
    private IPayerInfoService payerInfoService;
    @Autowired
    private IPayerBusinessInfoService payerBusinessInfoService;
    private static final Logger log = LoggerFactory.getLogger(BusinessCapitalController.class);

    @RequiresPermissions("channel:businessCapital:view")
    @GetMapping()
    public String businessCapital(ModelMap mmap) {
        mmap.put("roleId", ShiroUtils.getSysUser().getRoles().get(0).getRoleId());
        return prefix + "/businessCapital";
    }

    /**
     * 查询商户提现列表
     */
    @RequiresPermissions("channel:businessCapital:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BusinessCapital businessCapital) {
        startPage();
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        if (roleKey.equals("channel")) {
            businessCapital.getParams().put("channelUserId", ShiroUtils.getUserId());
        } else if (roleKey.equals("mall")) {
            businessCapital.setBusinessId(ShiroUtils.getUserId());
        } else if (roleKey.equals("agent")) {
            businessCapital.getParams().put("parentUserId", ShiroUtils.getUserId());
        } else if (roleKey.equals("salesman")) {
            businessCapital.getParams().put("rootUserId", ShiroUtils.getUserId());
        } else if (roleKey.equals("group")) {
            businessCapital.getParams().put("groupUserId", ShiroUtils.getUserId());
        }
        List<BusinessCapital> list = businessCapitalService.selectBusinessCapitalList(businessCapital);
        return getDataTable(list);
    }

    /**
     * 导出商户提现列表
     */
    @RequiresPermissions("channel:businessCapital:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BusinessCapital businessCapital) {
        List<BusinessCapital> list = businessCapitalService.selectBusinessCapitalList(businessCapital);
        ExcelUtil<BusinessCapital> util = new ExcelUtil<BusinessCapital>(BusinessCapital.class);
        return util.exportExcel(list, "businessCapital");
    }

    /**
     * 新增商户提现
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        // 查找当前登录账号下的银行卡号
        long start = System.currentTimeMillis();
        BankInfo bankInfo = new BankInfo();
        bankInfo.setUserId(ShiroUtils.getUserId());
        List<BankInfo> bankInfos = bankInfoService.selectBankInfoList(bankInfo);
        mmap.put("bankInfos", bankInfos);

        VwBusinessCashStat search = new VwBusinessCashStat();
        search.setUserId(ShiroUtils.getUserId());
        List<VwBusinessCashStat> vwBusinessCashStats = vwBusinessCashStatService.selectVwBusinessCashStatList(search);
        VwBusinessCashStat vwBusinessCashStat;
        if (vwBusinessCashStats.size() > 0) {
            vwBusinessCashStat = vwBusinessCashStats.get(0);
        } else {
            vwBusinessCashStat = new VwBusinessCashStat();
            vwBusinessCashStat.setFrzzingCash(BigDecimal.valueOf(0));
            vwBusinessCashStat.setCashSum(BigDecimal.valueOf(0));
        }
        mmap.put("vwBusinessCashStat", vwBusinessCashStat);
        log.info("获取商户提现信息结束时长:" + (System.currentTimeMillis() - start) + ";当前用户:" + ShiroUtils.getLoginName());

        BusinessCaptialSetting businessCaptialSetting = businessCaptialSettingService.selectBusinessCaptialSettingByBusiness(ShiroUtils.getUserId());
        if (businessCaptialSetting == null) {
            // 如果未特殊配置 则取系统默认设置
            businessCaptialSetting = businessCaptialSettingService.selectBusinessCaptialSettingByBusiness(1L);
        }
        mmap.put("businessCaptialSetting", businessCaptialSetting);
        return prefix + "/add";
    }

    /**
     * 新增商户提现
     */
    @GetMapping("/add1")
    public String add1(ModelMap mmap) {
        // 查找当前登录账号下的银行卡号
//        BankInfo bankInfo = new BankInfo();
//        bankInfo.setUserId(ShiroUtils.getUserId());
//        List<BankInfo> bankInfos = bankInfoService.selectBankInfoList(bankInfo);
//        mmap.put("bankInfos", bankInfos);

        VwBusinessCashStat search = new VwBusinessCashStat();
        search.setUserId(ShiroUtils.getUserId());
        PayerBusinessInfo searchB = new PayerBusinessInfo();
        searchB.setBusinessName("代理中心商户");
        List<PayerBusinessInfo> payerBusinessInfos = payerBusinessInfoService.selectPayerBusinessInfoList(searchB);

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("businessId=").append(payerBusinessInfos.get(0).getBusinessNo());
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        stringBuilder.append("&time=").append(time);
        stringBuilder.append("&").append(payerBusinessInfos.get(0).getApiKey());
        String sign = "";
        try {
            log.info("setToNextOrderString:" + stringBuilder.toString());
            sign = Md5Utils.androidMD5(stringBuilder.toString());
            System.out.println("setToNextOrderStringSign:" + sign);
        } catch (Exception e) {
        }
        RestTemplate restTemplate = new RestTemplate();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("businessId", payerBusinessInfos.get(0).getBusinessNo());
        jsonObject.put("time", time);
        jsonObject.put("sign", sign);
        PayerInfo payerInfo = payerInfoService.selectPayerInfoById(12521L); // 代理中心
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(jsonObject.toJSONString(), headers);
        JSONObject body = restTemplate.exchange(payerInfo.getApiKey(), HttpMethod.POST, entity, JSONObject.class).getBody();
        log.info("setToNextOrder:" + body.toJSONString());

//        mmap.put("payerBusinessInfo", payerBusinessInfos.get(0));

//        List<VwBusinessCashStat> vwBusinessCashStats = vwBusinessCashStatService.selectVwBusinessCashStatList(search);
//        VwBusinessCashStat vwBusinessCashStat;
//        if (vwBusinessCashStats.size() > 0) {
//            vwBusinessCashStat = vwBusinessCashStats.get(0);
//        } else {
//            vwBusinessCashStat = new VwBusinessCashStat();
//            vwBusinessCashStat.setFrzzingCash(BigDecimal.valueOf(0));
//            vwBusinessCashStat.setCashSum(BigDecimal.valueOf(0));
//        }
        mmap.put("vwBusinessCashStat", body.get("data"));
        mmap.put("businessCaptialSetting", body.getJSONObject("data").get("businessCaptialSetting"));
        return prefix + "/add1";
    }

    @GetMapping("/withdraw/info")
    @ResponseBody
    public AjaxResult getWithdrawInfo(ModelMap mmap) {
        // 查找当前登录账号下的银行卡号
        VwBusinessCashStat search = new VwBusinessCashStat();
        search.setUserId(ShiroUtils.getUserId());
        PayerBusinessInfo searchB = new PayerBusinessInfo();
        searchB.setBusinessName("代理中心商户");
        List<PayerBusinessInfo> payerBusinessInfos = payerBusinessInfoService.selectPayerBusinessInfoList(searchB);

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("businessId=").append(payerBusinessInfos.get(0).getBusinessNo());
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        stringBuilder.append("&time=").append(time);
        stringBuilder.append("&").append(payerBusinessInfos.get(0).getApiKey());
        String sign = "";
        try {
            log.info("setToNextOrderString:" + stringBuilder.toString());
            sign = Md5Utils.androidMD5(stringBuilder.toString());
            System.out.println("setToNextOrderStringSign:" + sign);
        } catch (Exception e) {
        }
        RestTemplate restTemplate = new RestTemplate();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("businessId", payerBusinessInfos.get(0).getBusinessNo());
        jsonObject.put("time", time);
        jsonObject.put("sign", sign);
        PayerInfo payerInfo = payerInfoService.selectPayerInfoById(12521L); // 代理中心
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(jsonObject.toJSONString(), headers);
        JSONObject body = restTemplate.exchange(payerInfo.getApiKey(), HttpMethod.POST, entity, JSONObject.class).getBody();
        log.info("setToNextOrder:" + body.toJSONString());
        mmap.put("vwBusinessCashStat", body.get("data"));
        mmap.put("businessCaptialSetting", body.getJSONObject("data").get("businessCaptialSetting"));
        return AjaxResult.success("success", mmap);
    }

    /**
     * 新增保存商户提现
     */
    @Log(title = "商户提现", businessType = BusinessType.INSERT)
    @PostMapping("/withdraw")
    @ResponseBody
    public AjaxResult withdraw(String amount) {
        PayerBusinessInfo searchB = new PayerBusinessInfo();
        searchB.setBusinessName("代理中心商户");
        List<PayerBusinessInfo> payerBusinessInfos = payerBusinessInfoService.selectPayerBusinessInfoList(searchB);

        StringBuilder stringBuilder = new StringBuilder();
//        stringBuilder.append("businessId=").append(payerBusinessInfos.get(0).getBusinessNo());
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
//        stringBuilder.append("&time=").append(time);
//        stringBuilder.append("&").append(payerBusinessInfos.get(0).getApiKey());
        String sign = "";
        stringBuilder.append("businessId=").append(payerBusinessInfos.get(0).getBusinessNo());
        stringBuilder.append("&payType=").append("107");
        stringBuilder.append("&childOrderno=").append(time);
        ;
        stringBuilder.append("&amount=").append(amount);
        stringBuilder.append("&time=").append(time);
        stringBuilder.append("&bankNo=");
        stringBuilder.append("&").append(payerBusinessInfos.get(0).getApiKey());

        try {
            log.info("setToNextOrderString:" + stringBuilder.toString());
            sign = Md5Utils.androidMD5(stringBuilder.toString());
            System.out.println("setToNextOrderStringSign:" + sign);
        } catch (Exception e) {
        }
        RestTemplate restTemplate = new RestTemplate();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("businessId", payerBusinessInfos.get(0).getBusinessNo());
        jsonObject.put("payType", "107");
        jsonObject.put("childOrderno", time);
        jsonObject.put("amount", amount);
        jsonObject.put("time", time);
        jsonObject.put("bankNo", "");
        jsonObject.put("sign", sign);
        PayerInfo payerInfo = payerInfoService.selectPayerInfoById(12521L); // 代理中心
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> entity = new HttpEntity<String>(jsonObject.toJSONString(), headers);
        JSONObject body = restTemplate.exchange(payerInfo.getRemark(), HttpMethod.POST, entity, JSONObject.class).getBody();
        log.info("setToNextOrder:" + body.toJSONString());
        if (body.getString("code").equals("500")) {
            return AjaxResult.error((body.getString("msg")));
        }
        return AjaxResult.success("success");
    }

    /**
     * 新增商户提现
     */
    @GetMapping("/add/info")
    @ResponseBody
    public AjaxResult add1() {
        HashMap<String, Object> mmap = new HashMap<>();
        // 查找当前登录账号下的银行卡号
        long start = System.currentTimeMillis();
        BankInfo bankInfo = new BankInfo();
        bankInfo.setUserId(ShiroUtils.getUserId());
        List<BankInfo> bankInfos = bankInfoService.selectBankInfoList(bankInfo);
        mmap.put("bankInfos", bankInfos);

        VwBusinessCashStat search = new VwBusinessCashStat();
        search.setUserId(ShiroUtils.getUserId());
        List<VwBusinessCashStat> vwBusinessCashStats = vwBusinessCashStatService.selectVwBusinessCashStatList(search);
        VwBusinessCashStat vwBusinessCashStat;
        if (vwBusinessCashStats.size() > 0) {
            vwBusinessCashStat = vwBusinessCashStats.get(0);
        } else {
            vwBusinessCashStat = new VwBusinessCashStat();
            vwBusinessCashStat.setFrzzingCash(BigDecimal.valueOf(0));
            vwBusinessCashStat.setCashSum(BigDecimal.valueOf(0));
        }
        mmap.put("vwBusinessCashStat", vwBusinessCashStat);
        log.info("获取商户提现信息结束时长:" + (System.currentTimeMillis() - start) + ";当前用户:" + ShiroUtils.getLoginName());

        BusinessCaptialSetting businessCaptialSetting = businessCaptialSettingService.selectBusinessCaptialSettingByBusiness(ShiroUtils.getUserId());
        if (businessCaptialSetting == null) {
            // 如果未特殊配置 则取系统默认设置
            businessCaptialSetting = businessCaptialSettingService.selectBusinessCaptialSettingByBusiness(1L);
        }
        mmap.put("businessCaptialSetting", businessCaptialSetting);
        return AjaxResult.success("success", mmap);
    }


    /**
     * 新增保存商户提现
     */
    @Log(title = "商户提现", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestBody Map<String, String> map) {
        String amount = map.get("amount");
        String bankId = map.get("bankId");
        BankInfo searchB = new BankInfo();
        searchB.setUserId(ShiroUtils.getUserId());
        searchB.setBankId(bankId);
        List<BankInfo> bankInfos = bankInfoService.selectBankInfoList(searchB);
        if (bankInfos.size() == 0) {
            return AjaxResult.error("bank info error");
        }

        BankInfo bankInfo = bankInfos.get(0);
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoByUserId(ShiroUtils.getUserId());
        if (businessInfo == null) {
            return AjaxResult.error("user info error");
        }

//        if(!businessInfoService.matches(password)){
//            return AjaxResult.error("支付密码不正确!");
//        }


        // 有还未提交的订单也不允许取现
        UserGoodsInfo searchGoods = new UserGoodsInfo();
        searchGoods.setPayStatus("NO_COMMIT");
        searchGoods.setUserId(ShiroUtils.getUserId());
        List<UserGoodsInfo>  userGoodsInfoList = userGoodsInfoService.selectUserGoodsInfoList(searchGoods);
        if(!userGoodsInfoList.isEmpty()) {
            return AjaxResult.error("order error");
        }

        VwBusinessCashStat search = new VwBusinessCashStat();
        search.setUserId(ShiroUtils.getUserId());
        VwBusinessCashStat vwBusinessCashStats = businessInfoService.getMyClickUserAmountInfo();

        if(Integer.parseInt(vwBusinessCashStats.getDaySum()) < vwBusinessCashStats.getUserLevelConfig().getTaskNum()) {
            // 当日已做任务数 不能小于50单
            return AjaxResult.error("task sum error");
        }

        if (vwBusinessCashStats.getFinalCash().compareTo(BigDecimal.valueOf(Double.valueOf(amount))) == -1) {
            return AjaxResult.error("amount error");
        }

        BusinessCaptialSetting businessCaptialSetting = businessCaptialSettingService.selectBusinessCaptialSettingByBusiness(1L);
        BigDecimal _amount = BigDecimal.valueOf(Double.valueOf(amount));
        if (_amount.compareTo(businessCaptialSetting.getMinAmount()) == -1) {
            // 提现金额不能小于最小提现金额
            return AjaxResult.error("amount error");
        }

        if (_amount.compareTo(businessCaptialSetting.getMaxAmount()) == 1) {
            // 提现金额不能大于最大提现金额
            return AjaxResult.error("amount error");
        }

        BusinessCapital capital = new BusinessCapital();
        Date date = new Date();
        capital.setCreateTime(date);
        BigDecimal tmp = BigDecimal.valueOf(Double.valueOf(amount)).multiply(vwBusinessCashStats.getUserLevelConfig().getCashOutFee());
        capital.setRealAmount(BigDecimal.valueOf(Double.valueOf(amount)).subtract(tmp)); // 提现金额-手续费=实际到账金额
        capital.setAmount(BigDecimal.valueOf(Double.valueOf(amount)));
        capital.setApplyTime(date);
        capital.setBusinessId(Long.parseLong(businessInfo.getBusinessId() + ""));
        capital.setStatus("1");
        capital.setCreateBy(ShiroUtils.getLoginName());
        capital.setBankName(bankInfo.getBankName());
        capital.setBranchBank(bankInfo.getBranchName());
        capital.setBankNo(bankInfo.getBankNo());
        capital.setUserName(bankInfo.getUserName());
        capital.setProvince(bankInfo.getProvince());
        capital.setFee(tmp);
        if (businessInfo.getOrderPrice() != null) {
            capital.setRemark("假人");
        } else {
            capital.setRemark("真人");
        }
        return toAjax(businessCapitalService.insertBusinessCapital(capital));
    }

    /**
     * 修改商户提现
     */
    @GetMapping("/edit/{capitalId}")
    public String edit(@PathVariable("capitalId") String capitalId, ModelMap mmap) {
        BusinessCapital businessCapital = businessCapitalService.selectBusinessCapitalById(capitalId);
        mmap.put("businessCapital", businessCapital);
        // 查找当前登录账号下的银行卡号
        BankInfo bankInfo = new BankInfo();
        bankInfo.setUserId(ShiroUtils.getUserId());
        List<BankInfo> bankInfos = bankInfoService.selectBankInfoList(bankInfo);
        mmap.put("bankInfos", bankInfos);
        return prefix + "/edit";
    }

    /**
     * 修改保存商户提现
     */
    @RequiresPermissions("channel:businessCapital:edit")
    @Log(title = "商户提现", businessType = BusinessType.UPDATE)
    @PostMapping("/editStatus")
    @ResponseBody
    public AjaxResult editStatus(String status, String id) {
        return businessCapitalService.changeStatus(status, id);
        // 接入代付系统
//        if(status.equals("2")){
//            // 驳回
//            return businessCapitalService.changeStatus(status, id);
//        }else{
//            BusinessCapital businessCapital = businessCapitalService.selectBusinessCapitalById(id);
//            List<BusinessRate> rates = businessRateService.selectBusinessRateList(new BusinessRate());
//            JSONObject jsonObject = thirdPayerService.setToNextWithdraw(businessCapital,rates.get(0));
//            if(jsonObject.getIntValue("") == 0){
//                businessCapital.setRemark("放款中");
//                businessCapitalService.updateBusinessCapital(businessCapital);
//                String msg = jsonObject.getString("msg");
//                if(null == msg){
//                    msg="success";
//                }
//                return AjaxResult.success(msg);
//            }else{
//                return AjaxResult.error(jsonObject.getString("msg"));
//            }
//        }
    }

    /**
     * 删除商户提现
     */
    @RequiresPermissions("channel:businessCapital:remove")
    @Log(title = "商户提现", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(businessCapitalService.deleteBusinessCapitalByIds(ids));
    }

}
